import datetime

from flask import Blueprint, render_template, request, flash, jsonify
from werkzeug.security import generate_password_hash, check_password_hash

import ver
from app import db, scheduler
from models import User

auth = Blueprint('auth', __name__)


@auth.route('/check', methods=['GET'])
def check_status():
    if 'id' in request.args.keys():
        user = User.query.filter_by(id=int(request.args.get('id'))).first()
        if user is not None:
            return jsonify({'success': True, 'logged_in': user.logged_in}), 200
        else:
            return jsonify({'success': False}), 200
    else:
        return jsonify({'success': False}), 200


@auth.route('/register', methods=['GET'])
def register():
    return render_template('register.html')


@auth.route('/register/ver', methods=['GET'])
def send_ver_code():
    if 'email' not in request.args:
        return jsonify({'sent': False}), 200
    email_address = request.args.get('email')
    user = User.query.filter_by(email_address=email_address).first()
    if user is None:
        # mail_worker.send('ver code', ver.generate(email_address), email_address)
        print(ver.generate(email_address))
        return jsonify({'success': True}), 200
    else:
        return jsonify({'success': False}), 200


@auth.route('/register', methods=['POST'])
def register_post():
    username = request.form.get('username')
    password = request.form.get('password')
    email_address = request.form.get('email')
    ver_code = request.form.get('ver')
    if not ver.verify(email_address, str(ver_code)):
        flash('ver code is not correct')
        return jsonify({'success': False}), 200
    user = User.query.filter_by(email_address=email_address).first()
    if user:
        flash('Email address already exists')
        return jsonify({'success': False}), 200

    new_user = User(
        email_address=email_address,
        username=username,
        password=generate_password_hash(password, method='sha256'),
        register_date=datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).astimezone(
            datetime.timezone(datetime.timedelta(hours=8))),
    )

    db.session.add(new_user)
    db.session.commit()
    return jsonify({
        'success': True,
        'email_address': new_user.email_address
    }, 200)


@auth.route('/login', methods=['GET'])
def login():
    return render_template('login.html')


# pass additional parameter as login indicator
@auth.route('/login', methods=['POST'])
def login_post():
    email_address = request.form.get('email')
    user = User.query.filter_by(email_address=email_address).first()
    password = request.form.get('password')
    if user and check_password_hash(user.password, password):
        user.logged_in = True
        db.session.commit()

        def expire_user(id):
            temp_user = User.query.filter_by(id=id).first()
            if temp_user:
                temp_user.logged_in = False

        scheduler.add_job(func=expire_user, args=(user.id,), trigger='cron',
                          day_of_week='mon-fri', hour=0, minute=0)

        return jsonify({
            'success': True,
            'user_id': user.id,
            'username': user.username,
            'email_address': user.email_address
        }), 200
    return jsonify({'success': False}), 200


@auth.route('/logout', methods=['POST'])
def logout():
    if 'id' in request.form:
        id = request.form.get('id')
        user = User.query.filter_by(id=id).first()
        if user is not None and user.logged_in:
            user.logged_in = False
        db.session.commit()
        return jsonify({'success': True}), 200
    else:
        return jsonify({'success': False}), 200
